use leptos::{prelude::*};
use shq_web_controls::{use_message, MessageOptions, MessageVariant};
use thaw_utils::ArcOneCallback;

use crate::{components::{ ButtonList, CommonPage, DataRange, DefaultButton}, shhr::init_password};
use icondata as i;
use serde_json::{Value};

#[component]
pub fn User(menu_id: u32, conf_name: Oco<'static, str>) -> impl IntoView {

    let mess = use_message();

    let init_user_password_action = Action::new(move |&(emid): &(u32)| {
        async move {
            match init_password(emid).await {
                Ok(_) => {
                    mess.create(
                        "初始化密码成功",
                        MessageVariant::Success,
                        MessageOptions::default(),
                    );
                }
                Err(e) => {
                    mess.create(
                        format!("初始化密码失败：{}", e),
                        MessageVariant::Error,
                        MessageOptions::default(),
                    );
                }
            }
        }
    });
    let init_password = ArcOneCallback::new(move |rows:Vec<Value>| {
        let row = rows[0].as_object().unwrap();
        let id_value = row.get("id").expect("返回值没有id");
        let emid = id_value.as_u64().expect("id不是u64类型");
        init_user_password_action.dispatch((emid as u32));
    });
    // 定义自定义按钮
    let custom_buttons = {
        let mut bl = ButtonList::new();
        bl.add_default(DefaultButton::Insert);
        bl.add_default(DefaultButton::Update);
        bl.add_default(DefaultButton::Delete);
        bl.add_default(DefaultButton::Import(true));
        bl.add_custom(
            "初始化密码".to_string(),
            Some(i::AiPlusCircleOutlined),
            None,
            Some("您确定要对选择员工进行密码初始化吗？".to_string()),
            DataRange::Selected,
            vec!["id"],
            init_password,
        );
        bl
    };

    view! {
        <div class="flex flex-1 gap-2 mx-2 w-full h-full overflow-hidden">
            <Suspense fallback=|| view! { <progress class="progress w-56"></progress> }>
                <CommonPage
                    menu_id=menu_id
                    conf_name=conf_name
                    custom_buttons=custom_buttons
                />
            </Suspense>
        </div>
    }.into_any()
}
